var stats = new Stats();
var sts = stats.domElement.style;
sts.position = 'absolute';
sts.top = '0px';
sts.right = '0px';
document.body.appendChild(stats.domElement);

var c = document.getElementById('c');
var ctx = c.getContext('2d');
var centerX, centerY, focalLength, startAnimal = true;
//处理宽高
window.addEventListener('resize', handleResize, false);
function handleResize(e) {
    c.width = window.innerWidth * window.devicePixelRatio;
    c.height = window.innerHeight * window.devicePixelRatio;
    centerX = c.width / 2;
    centerY = c.height / 2;
    focalLength = .5 * c.width;
}
handleResize();

//星星类
function Star(x, y, z, o) {
    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;
    this.o = o || 0;
    this.r = 0;
}
Star.starsNum = 1900;
Star.prototype = {
    update: function(ctx) {
        var pixelX, pixelY;
        this.z--;
        if(this.z <= 0) {
            this.z = c.width;
        }
        pixelX = (this.x - centerX) * (focalLength / this.z);
        pixelX += centerX;
        pixelY = (this.y - centerY) * (focalLength / this.z);
        pixelY += centerY;
        this.r = 1 * (focalLength / this.z);
        this.draw(ctx, pixelX, pixelY);
    },
    draw: function(ctx, pixelX, pixelY) {
        ctx.save();
        ctx.fillStyle = 'rgba(255, 255, 255, '+ this.o +')';
        ctx.fillRect(pixelX, pixelY, this.r, this.r);
        ctx.restore();
    }
}

//初始化
var stars = [];
for(var i = 0; i < Star.starsNum; i += 1) {
    stars.push(new Star(
        Math.random() * c.width,
        Math.random() * c.height,
        Math.random() * c.width,
        '0.' + Math.floor(Math.random() * 99) + 1
    ))
}

//动画函数
(function animate () {
    requestAnimationFrame(animate);
    stats.update();
    ctx.save();
    ctx.fillStyle = 'rgba(0, 10, 20, 1)';
    ctx.fillRect(0, 0, c.width, c.height);
    ctx.restore();  
    for(var i = 0; i < stars.length; i += 1) {
        stars[i].update(ctx);
    }
})()